﻿using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.ClientDW.DataAccessLayer;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities;
using Sustainalytics.Entities.Governance;
using Sustainalytics.Governance.BusinessLogic.Exceptions;
using Sustainalytics.Governance.BusinessLogic.Model;
using Sustainalytics.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace Sustainalytics.Governance.BusinessLogic
{
    public class GovernanceManager : IGovernanceManager
    {
        private readonly IClientDwRepository _clientDwRepository;
        private readonly IRepositoryCollection<GovernanceInsightInputFile> _governanceInputFileRepository = null;
        private readonly IRepositoryCollection<GovernanceInsightInputFile> _governanceInputFileRepositoryWithFiles = null;
        private readonly IRepositoryCollection<GovernancePdfProfileMetadata> _governancePdfProfileMetadataRepository = null;

        private readonly IGovernanceRepository _governanceRepository;
        private readonly string _baseUrl;

        public static GovernanceManager CreateGovernanceManager(
            string clientDwConnectionString, 
            string governanceDwConnectionString, 
            string governanceInputFileConnectionString)
        {            
            var clientDwRepository = ClientDwRepository.GetInstance(clientDwConnectionString);
            var governanceRepository = new GovernanceRepository(governanceDwConnectionString);
            var baseUrl = ConfigurationManager.AppSettings["ClientPlatformUrl"];

            var governanceInputFileRepository = new RepositoryCollection<GovernanceInsightInputFile>(governanceInputFileConnectionString);
            var governanceInputFileRepositoryWithFiles = new RepositoryCollectionWithFile<GovernanceInsightInputFile>(governanceInputFileConnectionString);
            var governancePdfProfileMetadataRepository = new RepositoryCollection<GovernancePdfProfileMetadata>(governanceInputFileConnectionString);

            return new GovernanceManager(
                clientDwRepository,
                governanceRepository,
                governanceInputFileRepository,
                governanceInputFileRepositoryWithFiles,
                governancePdfProfileMetadataRepository,
                baseUrl);
        }

        public GovernanceManager(IClientDwRepository clientDwRepository,
            IGovernanceRepository governanceRepository,
            IRepositoryCollection<GovernanceInsightInputFile> governanceInputFileRepository,
            IRepositoryCollection<GovernanceInsightInputFile> governanceInputFileRepositoryWithFiles,
            IRepositoryCollection<GovernancePdfProfileMetadata> governancePdfProfileMetadataRepository,
            string baseUrl)
        {
            _clientDwRepository = clientDwRepository;
            _governanceRepository = governanceRepository;
            _baseUrl = baseUrl;
            _governanceInputFileRepository = governanceInputFileRepository;
            _governanceInputFileRepositoryWithFiles = governanceInputFileRepositoryWithFiles;
            _governancePdfProfileMetadataRepository = governancePdfProfileMetadataRepository;
        }
               
        public string ReadPdfFileName(Guid id)
        {
            if (id == Guid.Empty)
                throw new ArgumentNullException("id");
            var file = _governanceInputFileRepository.ReadWhere(x => x.FileId == id).FirstOrDefault();
            var ret = "";
            if (file != null)
            {
                ret = file.FileName;
            }
            return ret;
        }
        
        private string GetReportType(Guid companyId)
        {
            var governancePdfProfile = _governancePdfProfileMetadataRepository.ReadAllWhere(x => x.CompanyId == companyId
                && x.GovernancePdfType == GovernancePdfType.GovernanceDataProfile
                && x.OperationType != UpdateOperationType.Deleted).SingleOrDefault();

            var reportType = (governancePdfProfile == null) ? "Report" : "CompanyReport";

            return reportType;
        }

        public GovernanceProfileDto GetProfileByCompany(Guid companyId)
        {
            //read governance profile from governance repository
            var gProfile = _governanceRepository.ReadByCompanyId(companyId);
            
            if (gProfile == null)
            {
                throw new GovernanceProfileNotFoundException();
            }

            //sorting insights by publication date desc
            if (gProfile.Insights == null)
                gProfile.Insights = new List<GovernanceInsight>();
            gProfile.Insights = gProfile.Insights.OrderByDescending(x => x.PublicationDate).ToList();
            
            var result = GovernanceProfileDto.FromGovernanceProfile(gProfile, _baseUrl,GetCompanyProfileMetadata(companyId));

            result.ReportType = GetReportType(companyId);

            //populate filenames for company insights
            result.Insights.ForEach(x =>
            {
                x.FileName = ReadPdfFileName(x.FileId);
            });
            
            return result;
        }

        public GovernanceProfileDto GetProfileByCompany(Guid companyId, List<int> userUniverseIds)
        {
            var gProfile = _governanceRepository.ReadByCompanyId(companyId);
            var pdfData = GetCompanyProfileMetadata(companyId);

            var corpData = _clientDwRepository.GetCorporateDataByCompanyId(companyId);
            if (corpData == null)
            {
                throw new CorporateDataGovernanceNotFoundException(string.Format("The company:{0} was not found", companyId));
            }
            else
            {
                if (corpData.UniverseIds == null || !corpData.UniverseIds.ContainsAny(userUniverseIds))
                    throw new GovernanceProfileNotInUniversesException();

                if (corpData.CorporateGovernanceResearchState.ResearchState == ResearchState.FrameworkNotApplicable)
                    throw new GovernanceResearchStateFrameworkNotApplicable("The company has corporate governance research state framework not applicable");

                if (corpData.CorporateGovernanceResearchState.ResearchState == ResearchState.ResearchInProgress)
                    throw new GovernanceResearchStateInProgressException("The company has corporate governance research state in progress");

                if (corpData.CorporateGovernanceResearchState.ResearchState != ResearchState.ResearchAvailable)
                    throw new GovernanceResearchFlagInvalidException("The company does not have corporate governance research flag true");
            }

            if (gProfile == null)
                throw new GovernanceProfileNotFoundException();

            //sorting insights by publication date desc
            gProfile.Insights = gProfile.Insights == null ? new List<GovernanceInsight>() : gProfile.Insights.OrderByDescending(x => x.PublicationDate).ToList();

            var result = GovernanceProfileDto.FromGovernanceProfile(gProfile, _baseUrl, pdfData);

            result.ReportType = GetReportType(companyId);

            //populate filenames for company insights
            result.Insights.ForEach(x =>
            {
                x.FileName = this.ReadPdfFileName(x.FileId);
            });


            return result;
        }

        private GovernancePdfProfileMetadata[] GetCompanyProfileMetadata(Guid companyId)
        {
            var pdfData =
                _governancePdfProfileMetadataRepository
                    .Collection()
                    .Find(Builders<GovernancePdfProfileMetadata>.Filter.Eq(a => a.CompanyId, companyId))
                    .Project<GovernancePdfProfileMetadata>(Builders<GovernancePdfProfileMetadata>.Projection
                        .Include(a => a.Id)
                        .Include(a => a.CompanyId)
                        .Include(a => a.GovernancePdfType)
                        .Include(a => a.OperationType)
                        .Include(a => a.LastOperationDateTime))
                    .ToList()
                    .ToArray();

            return pdfData;
        }


        public CorporateData GetCorporateDataById(Guid companyId)
        {
            return _clientDwRepository.GetCorporateDataByCompanyId(companyId);
        }

        public GovernancePdfProfileMetadataDto UpdateGovernancePdfProfileMetadata(GovernancePdfProfileMetadataDto profile, string userName)
        {
            return new GovernancePdfProfileMetadataDto();
        }
      
        public GovernanceProfileDto AddInsight(GovernanceInsight insight, GovernanceInsightInputFile inputFile)
        {
            var gProfile = _governanceRepository.ReadByCompanyId(inputFile.CompanyId);
            if (gProfile.Insights == null)
                gProfile.Insights = new List<GovernanceInsight>();
            bool shouldAddInsight = true;
            var oldInsight = gProfile.Insights.FirstOrDefault(x => x.Id == insight.Id);
            if (oldInsight != null)
            {
                oldInsight.PublicationDate = insight.PublicationDate;
                oldInsight.Title = insight.Title;
                oldInsight.CreatedBy = insight.CreatedBy;
                oldInsight.CreatedDate = insight.CreatedDate;

                if (oldInsight.FileId == insight.FileId)
                    shouldAddInsight = false;
                else
                {
                    _governanceInputFileRepositoryWithFiles.Delete(oldInsight.FileId);
                    _governanceInputFileRepository.DeleteWhere(ins => ins.FileId == oldInsight.FileId);
                    gProfile.Insights.Remove(oldInsight);                    
                }                
            }
            if (shouldAddInsight)
            {
                gProfile.Insights.Add(insight);
                _governanceInputFileRepository.Create(inputFile);
            }
            _governanceRepository.Update(gProfile);
            return GetProfileByCompany(gProfile.Id);
        }

        public void DeleteInsight(Guid insightId, Guid companyId)
        {
            //remove the insight by id
            var gProfile = _governanceRepository.ReadByCompanyId(companyId);

            //this is the insight to delete
            var insight = gProfile.Insights.FirstOrDefault(ins => ins.Id == insightId);

            _governanceInputFileRepositoryWithFiles.Delete(insight.FileId);

            gProfile.Insights.Remove(insight);
            _governanceRepository.Update(gProfile);

            _governanceInputFileRepository.DeleteWhere(ins => ins.FileId == insight.FileId);
        }

        public void DeleteInsightByFileId(Guid fileId, Guid companyId)
        {
            //remove the insight by id
            var gProfile = _governanceRepository.ReadByCompanyId(companyId);

            //this is the insight to delete
            var insight = gProfile.Insights.FirstOrDefault(ins => ins.FileId == fileId);

            gProfile.Insights.Remove(insight);
            _governanceRepository.Update(gProfile);
        }
    }
}
